package com.zzyl.nursing.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.nursing.service.WechatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class WechatServiceImpl implements WechatService {

    // 登录
    private static final String REQUEST_URL = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code";

    // 获取token
    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";

    // 获取手机号
    private static final String PHONE_REQUEST_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";

    @Value("${wechat.appId}")
    private String appId;
    @Value("${wechat.appSecret}")
    private String secret;


    /**
     * 获取openid
     *
     * @param code
     * @return
     */
    @Override
    public String getOpenId(String code) {
        //准备请求参数
        HashMap<String, Object> params = new HashMap<>();
        params.put("appid", appId);
        params.put("secret", secret);
        params.put("js_code", code);


        //发送请求
        String jsonObject = HttpUtil.get(REQUEST_URL, params);

        JSONObject entries = JSONUtil.parseObj(jsonObject);


        if (ObjectUtil.isNotEmpty(entries.getInt("errcode"))) {
            throw new RuntimeException("失败");
        }

        String openid = entries.getStr("openid");


        return openid;
    }

    /**
     * 获取手机号
     *
     * @param phoneCode
     */
    @Override
    public String getPhone(String phoneCode) {
        Map<String, Object> params = new HashMap<>();
        params.put("code", phoneCode);

        String accessToken = GetAccessToken();

        String post = HttpUtil.post(PHONE_REQUEST_URL + accessToken, JSONUtil.toJsonStr(params));

        JSONObject entries = JSONUtil.parseObj(post);

        if (!entries.getInt("errcode").equals(0)) {
            throw new BaseException("获取手机号失败");
        }

        JSONObject phoneInfo = entries.getJSONObject("phone_info");
        String phoneNumber = phoneInfo.getStr("phoneNumber");

        return phoneNumber;
    }

    private String GetAccessToken() {
        //准备请求参数
        HashMap<String, Object> params = new HashMap<>();
        params.put("appid", appId);
        params.put("secret", secret);
        params.put("grant_type", "authorization_code");


        //发送请求
        String jsonObject = HttpUtil.get(TOKEN_URL, params);

        JSONObject entries = JSONUtil.parseObj(jsonObject);


        if (ObjectUtil.isNotEmpty(entries.getInt("errcode"))) {
            throw new RuntimeException("失败");
        }

        String openid = entries.getStr("access_token");


        return openid;
    }
}
